package com.shenghua.utils;

import com.alibaba.fastjson.JSON;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTempTopic;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.*;
//import javax.jms.*;

/**
 * Created by Administrator on 2019/5/22.
 */
@Component
public class MqUtils {
    private static Logger logger = LoggerFactory.getLogger(MqUtils.class);
    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Resource
    private JmsTemplate jmsTemplate;

    /**
     * 发送队列模式消息
     * @param target 队列标识
     *
     */
    public void sendQueueMessage(String target, Object message) {
        //Queue queue = new ActiveMQQueue(target);// 生成队列
        //jmsMessagingTemplate.convertAndSend(queue, message);// 往队列中放入消息
        jmsTemplate.send(target, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage = session.createTextMessage();
                textMessage.setText(JSON.toJSONString(message));
                return textMessage;
            }
        });
        logger.info("队列加入消息：{}", JSON.toJSONString(message));
    }

    /**
     * 发送发布订阅模式消息
     */
    public void sendTopicMessage(String target, Object message) {
        Topic topic = new ActiveMQTopic(target);// 生成主题
        jmsMessagingTemplate.convertAndSend(topic, JSON.toJSONString(message));//往主题中放入消息
        logger.info("主题加入消息：{}", JSON.toJSONString(message));
    }
}
